import { Reducer, Subscription } from 'umi';
import { Effect } from '@@/plugin-dva/connect';
import { addRecord, deleteRecord, editRecord, getRemoteList } from '@/pages/users/service';
import { message } from 'antd';

interface UserModelType {
  namespace: 'users';
  state: {};
  reducers: {
    getList: Reducer
  };
  effects: {
    getRemote: Effect,
    edit: Effect
    add: Effect,
    delete: Effect,
  };
  subscriptions: {
    setup: Subscription;
  };
}

const UserModel: UserModelType = {
  namespace: 'users',
  state: {},
  reducers: {
    getList(state, { payload }) {
      return payload;
    },
  },
  effects: {
    * getRemote({ payload }, { call, put }) {
      const data = yield call(getRemoteList);
      if (data) {
        yield put({
          type: 'getList',
          payload: data,
        });
      }
    },
    * edit({ payload: { id, values } }, { put, call }) {
      const result = yield call(editRecord, id, values);
      if (result) {
        yield put({
          type: 'getRemote',
        });
        message.info('edit success');
      }
    },
    * add({ payload: { values } }, { put, call }) {
      const result = yield call(addRecord, values);
      if (result) {
        yield put({
          type: 'getRemote',
        });
        message.info('add success');
      }
    },
    * delete({ payload: { id } }, { put, call }) {
      const result = yield call(deleteRecord, id);
      if (result) {
        yield put({
          type: 'getRemote',
        });
        message.info('delete success');
      }
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/users') {
          dispatch({
            type: 'getRemote',
          });
        }
      });

    },
  },
};

export default UserModel;
